package com.android.dx.webanalystjx.app;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

/**
 * Author: Ligang
 * Date: 2019/11/19
 * Description:缓存管理
 */
public class SharePreManager {
    public static final String TAG = SharePreManager.class.getName();
    private static final String DEFAULT_SHARED_PRE_NAME = "appdata";

    private static SharedPreferences getPre(String preName) {
        return App.instance.getSharedPreferences(preName, Context.MODE_PRIVATE);
    }

    private static SharedPreferences getDefaultPre() {
        return getPre(DEFAULT_SHARED_PRE_NAME);
    }

    private static <T> void saveCacheObj(SharedPreferences preferences, String jsonKey, T obj) {
        if (obj == null) {
            preferences.edit().putString(jsonKey, "").apply();
            return;
        }
        if (obj instanceof String) {
            preferences.edit().putString(jsonKey, obj.toString()).apply();
        } else {
            preferences.edit().putString(jsonKey, App.gson.toJson(obj)).apply();
        }
    }

    private static <T> T getCacheObj(SharedPreferences preferences, String jsonKey, Class<T> clz) {
        String json = preferences.getString(jsonKey, null);
        if (!TextUtils.isEmpty(json)) {
            if (clz.getName().equals(String.class.getName())) {
                return (T) json;
            }
            try {
                return App.gson.fromJson(json, clz);
            } catch (Exception e) {

            }
        }
        return null;
    }

    public static void savePtkey(String ptkey) {
        saveCacheObj(getDefaultPre(), "jx_ptkey", ptkey);
    }

    public static String getPtkey() {
        return getCacheObj(getDefaultPre(), "jx_ptkey", String.class);
    }
}
